<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends ComController
{

    //前台首页
    public function index(){

        $url = '/login';
        $this->redirect("$url");
    }

    //登录
    public function login(){
        //通告
        $toDay= strtotime(date('Y-m-d', time()));
        $inform = M('inform')->where('end >'.$toDay)->order('end desc')->limit('10')->select();
        $this->assign('inform',$inform);
        $this->assign('toDay',$toDay);
        if(IS_POST)
        {
            $verify = isset($_POST['code'])?trim($_POST['code']):'';
            if (!checkverify($verify)) {
                $info = array(
                    "info"=>"验证码不正确！",
                    "status"=>"n",
                );
                $this -> ajaxReturn($info,'json');
            }

            $username = isset($_POST['user'])?trim($_POST['user']):'';
            $password = isset($_POST['password'])?password(trim($_POST['password'])):'';
            $remember = isset($_POST['remember'])?$_POST['remember']:0;
            if ($username=='') {
                $info = array(
                    "info"=>"用户名不能为空!",
                    "status"=>"n",
                );
                $this -> ajaxReturn($info,'json');
            } elseif ($password=='') {
                $info = array(
                    "info"=>"密码必须填写!",
                    "status"=>"n",
                );
                $this -> ajaxReturn($info,'json');
            }

            $model = M("Member");
            $user = $model ->field('uid,user')-> where(array('user'=>$username,'password'=>$password)) -> find();

            if($user) {
                $token = password(uniqid(rand(), TRUE));
                $salt = random(10);
                $identifier = password($user['uid'].md5($user['user'].$salt));
                $auth = $identifier.','.$token;
                $time = time();
                M('member')->data(array('identifier'=>$identifier,'token'=>$token,'salt'=>$salt,'t'=>$time))->where(array('uid'=>$user['uid']))->save();

                if($remember){
                    cookie('auth',$auth,3600*24*365);//记住我
                }else{
                    cookie('auth',$auth);
                }
                addlog('登录成功。');
                $info = array(
                    "info"=>"登录成功!",
                    "status"=>"y",
                );
                $this -> ajaxReturn($info,'json');
                exit(0);
            }else{
                addlog('登录失败。',$username);
                $info = array(
                    "info"=>"登录失败请检查用户名或密码重新登录!",
                    "status"=>"n",
                );
                $this -> ajaxReturn($info,'json');
            }
        }

        $this->display('login');

    }

    //注册
    public function reg(){

        $this->display('reg');
    }


}